//
//  MBScanViewController.m
//  MemberBusiness-ios
//
//  Created by 掌心 on 2018/5/31.
//  Copyright © 2018年 zhangXin. All rights reserved.
//

#import "MBScanViewController.h"
#import "MBQRCodeBgView.h"
#import <AssetsLibrary/AssetsLibrary.h>
#import "MBScanPreviewViewController.h"

@interface MBScanViewController ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate>
@property (nonatomic,strong) UIImagePickerController* imagePickerController;
@end

@implementation MBScanViewController
@dynamic viewModel;
- (void)viewDidLoad {
    [super viewDidLoad];

    [self setupLayout];
}

#pragma mark - lazy load
-(UIImagePickerController *)imagePickerController
{
    if (_imagePickerController == nil) {
        _imagePickerController = [[UIImagePickerController alloc]init];
        _imagePickerController.delegate = self;
    }
    return _imagePickerController;
}

-(void)setupLayout
{
    [super setupLayout];
    self.viewModel.superView = self.view;
    self.naviView.titleLabel.text = @"扫一扫";
    [self.naviView setUpBackButton];
    
    @weakify(self);
    [[self.naviView.backButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        @strongify(self);
        [self.navigationController popViewControllerAnimated:YES];
    }];
    
    MBQRCodeBgView *qrView=[[MBQRCodeBgView alloc]initWithFrame:CGRectMake(0, 44+SCREEN_STATUS_BAR_HEIGHT, SCREEN_WIDTH, SCREEN_HEIGHT-SCREEN_STATUS_BAR_HEIGHT-44)];
    [self.view addSubview:qrView];
    [self.viewModel startScan];
    
    [[qrView.photoButton rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(__kindof UIControl * _Nullable x) {
        @strongify(self);
        [self clickPhoto];
    }];
    
    [[qrView.scanButton rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(__kindof UIControl * _Nullable x) {
        @strongify(self);
    }];

}

/**
 *  点击拍照
 */
-(void)clickPhoto
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        if([[[UIDevice currentDevice] systemVersion] floatValue]>=8.0) {
            self.modalPresentationStyle=UIModalPresentationNone;
        }
        NSString *tipTextWhenNoPhotosAuthorization; // 提示语
        // 获取当前应用对照片的访问授权状态
        AVAuthorizationStatus authorizationStatus =[AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
        // 如果没有获取访问授权，或者访问授权状态已经被明确禁止，则显示提示语，引导用户开启授权
        if (authorizationStatus == ALAuthorizationStatusRestricted || authorizationStatus == ALAuthorizationStatusDenied) {
            NSDictionary *mainInfoDictionary = [[NSBundle mainBundle] infoDictionary];
            NSString *appName = [mainInfoDictionary objectForKey:@"CFBundleDisplayName"];
            tipTextWhenNoPhotosAuthorization = [NSString stringWithFormat:@"请在设备的\"设置-隐私-相机\"选项中，允许%@访问你的相机", appName];
            // 展示提示语
            dispatch_async(dispatch_get_main_queue(), ^{
                [[[UIAlertView alloc]initWithTitle:nil message:tipTextWhenNoPhotosAuthorization delegate:nil cancelButtonTitle:@"确定" otherButtonTitles: nil] show];
            });
            return;
        }
        //            拍照
        dispatch_async(dispatch_get_main_queue(), ^{
            self.imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            [self presentViewController:self.imagePickerController animated:YES completion:nil];
        });
    });
}

#pragma mark - UIImagePickerControlerDelegate delegate
- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated
{
    if ([navigationController isKindOfClass:[UIImagePickerController class]]) {
        if (((UIImagePickerController *)navigationController).sourceType == UIImagePickerControllerSourceTypePhotoLibrary) {
            [((UIImagePickerController *)navigationController).navigationBar setBarTintColor:COLOR_MAIN];
            [((UIImagePickerController *)navigationController).navigationBar setTitleTextAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:18],NSForegroundColorAttributeName:[UIColor whiteColor]}];
        }else {
            [navigationController setNavigationBarHidden:YES animated:YES];
        }
    }
}

-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    @weakify(self);
    [picker dismissViewControllerAnimated:YES completion:^{
        @strongify(self);
        UIImage * originalImage = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
        originalImage = [originalImage fixOrientation];
        MBScanPreviewViewController* previewVC = [[MBScanPreviewViewController alloc]initWithViewModel:[[MBScanPreviewViewModel alloc]init]];
        previewVC.scanImage = originalImage;
        [self.navigationController pushViewController:previewVC animated:YES];
    }];
}


@end
